package com.cyt.work.association.service.impl;

import cn.hutool.core.date.DateUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysFile;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.model.vo.SysFileVo;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.work.association.dao.WxAssociationDao;
import com.cyt.work.association.model.po.WxAssociation;
import com.cyt.work.association.model.vo.WxAssociationVo;
import com.cyt.work.association.service.WxAssociationService;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 社团管理-社团管理Service层实现类
 *
 * @author han jun
 * @date 2019-8-30 16:06:11
 */
@Service("wxAssociationService")
public class WxAssociationServiceImpl extends BaseServiceImpl<WxAssociation> implements WxAssociationService {

    @Resource
    private WxAssociationDao wxAssociationDao;

    @Resource
    private SysFileService sysFileService;

    @Autowired
    private WxEducationUserService wxEducationUserService;

    @Autowired
    public void setBaseDao(WxAssociationDao wxAssociationDao) {
        this.baseDao = wxAssociationDao;
    }

    /**
     * 查询对象集合
     *
     * @param wxAssociationVo 对象
     * @return List 对象集合
     * @author han jun
     * @date 2019-8-30 16:06:11
     */
    @Override
    public List<WxAssociation> listExample(WxAssociationVo wxAssociationVo) {
        Example example = new Example(WxAssociation.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        if (StringUtils.isNotBlank(wxAssociationVo.getId())) {
            criteria.andEqualTo("id",wxAssociationVo.getId());
        }
        if (StringUtils.isNotBlank(wxAssociationVo.getTitle())) {
            criteria.andLike("title", "%" + wxAssociationVo.getTitle() + "%");
        }
        if (StringUtils.isNotBlank(wxAssociationVo.getApplyId())) {
            criteria.andEqualTo("applyId",wxAssociationVo.getApplyId());
        }
        return wxAssociationDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param wxAssociationVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author han jun
     * @date 2019-8-30 16:06:11
     */
    @Override
    public ReturnResult page(WxAssociationVo wxAssociationVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");

        Example example = new Example(WxAssociation.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAssociationVo.getTitle())) {
            criteria.andLike("title", "%" + wxAssociationVo.getTitle() + "%");
        }
        if (StringUtils.isNotBlank(wxAssociationVo.getUserName())) {
            criteria.andLike("userName", "%" + wxAssociationVo.getUserName() + "%");
        }
        if (StringUtils.isNotBlank(wxAssociationVo.getApplyId())) {
            criteria.andEqualTo("applyId",wxAssociationVo.getApplyId());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        List<WxAssociation> list = wxAssociationDao.selectByExample(example);

        List<WxAssociation> newlist = new ArrayList<>();
        if (wxAssociationVo.getSelectIds()!=null&&wxAssociationVo.getSelectIds().length()>0){
            String[] ids  =wxAssociationVo.getSelectIds().split(",");
            for (WxAssociation wxAssociation:list){
                if (!Arrays.asList(ids).contains(wxAssociation.getId())){
                    newlist.add(wxAssociation);
                }
            }
            PageInfo<WxAssociation> page = new PageInfo<>(newlist);
            return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
        }else {
            PageInfo<WxAssociation> page = new PageInfo<>(list);
            return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
        }

    }

    /**
     * 添加或更新
     *
     * @param wxAssociationVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-8-30 16:06:11
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(WxAssociationVo wxAssociationVo, SysUser sysUser) {
        if (StringUtils.isBlank(wxAssociationVo.getId())) {
            WxAssociation wxAssociation = new WxAssociation(sysUser);
            wxAssociation.setApplyId(wxAssociationVo.getApplyId());
            wxAssociation.setTitle(wxAssociationVo.getTitle());
            wxAssociation.setUserNumber(wxAssociationVo.getUserNumber());
            wxAssociation.setUserName(wxAssociationVo.getUserName());
            wxAssociation.setOriginalPath(wxAssociationVo.getOriginalPath());
            wxAssociation.setPath(getFilePath(wxAssociationVo.getOriginalPath()));
            wxAssociation.setIntroduction(wxAssociationVo.getIntroduction());
            wxAssociationDao.insert(wxAssociation);
            //saveEductionUserList(wxAssociationVo,sysUser);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WxAssociation wxAssociation = wxAssociationDao.selectByPrimaryKey(wxAssociationVo.getId());
            wxAssociation.setApplyId(wxAssociationVo.getApplyId());
            wxAssociation.setTitle(wxAssociationVo.getTitle());
            wxAssociation.setUserNumber(wxAssociationVo.getUserNumber());
            wxAssociation.setUserName(wxAssociationVo.getUserName());
            wxAssociation.setOriginalPath(wxAssociationVo.getOriginalPath());
            wxAssociation.setIntroduction(wxAssociationVo.getIntroduction());
            wxAssociation.setPath(getFilePath(wxAssociationVo.getOriginalPath()));
            wxAssociation.setUpdateTime(new Date());
            wxAssociation.setUpdateUser(sysUser.getId());
            wxAssociationDao.updateByPrimaryKey(wxAssociation);
            //saveEductionUserList(wxAssociationVo,sysUser);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }
    private void saveEductionUserList(WxAssociationVo wxAssociationVo,SysUser sysUser){
        List<WxEducationUser> wxEducationUserList = new ArrayList<>();
        List<WxEducationUser> wxEducationUserShow = new ArrayList<>();
        String[] numbers = wxAssociationVo.getUserNumber().split(",");
        String[] names = wxAssociationVo.getUserName().split(",");
        //根据学号去更新姓名 没有这个学号就新建他的情况
        for (int i = 0;i<numbers.length;i++) {
            WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
            wxEducationUserVo.setUserNumber(numbers[i]);
            wxEducationUserVo.setCreateUser(sysUser.getId());
            List<WxEducationUser> list = wxEducationUserService.listExample(wxEducationUserVo);
            if (list != null && list.size() > 0) {
                for (WxEducationUser wxEducationUser:list){
                    if (!wxEducationUser.getName().equals(names[i])){
                        wxEducationUser.setName(names[i]);
                        wxEducationUserService.updateByPrimaryKey(wxEducationUser);
                    }

                }
                wxEducationUserShow.addAll(list);
                //更新姓名啥的
                continue;
            }
            // 账号不存在，保存进用户表
            WxEducationUser wxEducationUser = new WxEducationUser();
            wxEducationUser.setId(BaseUtil.uId());
            wxEducationUser.setLoginName(numbers[i]);
            wxEducationUser.setMobile("");
            wxEducationUser.setName(names[i]);
            wxEducationUser.setUserNumber(numbers[i]);
//            if (org.apache.commons.lang3.StringUtils.isNotEmpty(userFrom.getMobile()) && userFrom.getMobile().length() == 11) {
//                wxEducationUser.setPassword(MD5Util.MD5Encode(StrUtil.sub(userFrom.getMobile(), 5, 11)));
//            } else {
                wxEducationUser.setPassword(MD5Util.MD5Encode(BaseConstant.DEFAULT_EDUCATION_USER_PASSWORD));
//            }
//            wxEducationUser.setUserType("2");
            wxEducationUser.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            wxEducationUser.setCreateUser(sysUser.getId());
            wxEducationUser.setUpdateUser(sysUser.getId());
            wxEducationUser.setCreateTime(DateUtil.date());
            wxEducationUser.setUpdateTime(DateUtil.date());
            wxEducationUserList.add(wxEducationUser);
            wxEducationUserShow.add(wxEducationUser);
        }
        // 保存
        if (wxEducationUserList != null && wxEducationUserList.size() > 0) {
            wxEducationUserService.insertList(wxEducationUserList);
        }

    }



    /**
     * 根据条件逻辑删除
     *
     * @param wxAssociationVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-8-30 16:06:11
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WxAssociationVo wxAssociationVo, SysUser sysUser) {
        //要修改的字段
        WxAssociation wxAssociation = new WxAssociation();
        wxAssociation.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wxAssociation.setUpdateUser(sysUser.getId());
        wxAssociation.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WxAssociation.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAssociationVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxAssociationVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wxAssociationDao.updateByExampleSelective(wxAssociation, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param wxAssociationVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author han jun
     * @date 2019-8-30 16:06:11
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(WxAssociationVo wxAssociationVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(WxAssociation.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAssociationVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxAssociationVo.getId().split(",")));
        }
        wxAssociationDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    private String getFilePath(String ObjectId) {
        SysFileVo sysFileVo = new SysFileVo(ObjectId);
        List<SysFile> sysFileList = sysFileService.listExample(sysFileVo);
        if (sysFileList != null && sysFileList.size() == 1) {
            return sysFileList.get(0).getPath();
        }
        return "";
    }
}